package com.frank.service.nettydemo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @Author: huweifeng
 * @Date: 2025/2/7
 * @Description:
 * Channel主要功能：
 * close()关闭channel
 * closeFuture()处理关闭后的问题
 * - sync()方法作用是同步等待channel关闭
 * - addListener方法是异步等待channel关闭
 * pipeline()方法添加处理器
 * write()方法将数据写入
 * writeAndFlush()方法将数据写入并刷出
 **/
public class ChannelDemo {
    public static void main(String[] args) throws InterruptedException {
        ChannelFuture channelFuture = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        channel.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect("localhost", 8080);

        // 方法一
        Channel channel = channelFuture.sync().channel();
        channel.writeAndFlush("hello world");

        // 方法二
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                channelFuture.channel().writeAndFlush("hello world");
            }
        });
    }
}
